package com.sky.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sky.exception.OrderBusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class BaiduMapUtil {

    public static final String URL = "https://api.map.baidu.com/geocoding/v3?";

    public static final String RIDE_URL = "https://api.map.baidu.com/direction/v2/riding";

    @Value("${sky.baidu.ak}")
    public String AK;

    @Value("${sky.shop.range}")
    public Integer range;


    /**
     * 根据地址获取经纬度
     *
     * @param address
     * @return
     */
    public String getLocation(String address) {
        //构建请求参数
        Map params = new LinkedHashMap<String, String>();
        params.put("address", address);
        params.put("output", "json");
        params.put("ak", AK);

        //返回json数据
        String lngLat = HttpClientUtil.doGet(URL, params);

        //解析json
        JSONObject jsonObject = JSONObject.parseObject(lngLat);
        String status = jsonObject.getString("status");
        if (!status.equals("0")) {
            //status!=0  抛异常
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //result location 获得Lng Lat
        JSONObject object = jsonObject.getJSONObject("result").getJSONObject("location");
        String lng = object.getString("lng");
        String lat = object.getString("lat");

        String[] split1 = lng.split("\\.");
        lng = split1[0] + "." + split1[1].substring(0, 6);

        String[] split = lat.split("\\.");
        lat = split[0] + "." + split[1].substring(0, 6);

        //拼接 lat lng  返回 字符串
        return lat + "," + lng;
    }


    public boolean checkOutOfRange(String userLocation, String shopLocation) {
        //构建请求参数
        Map params = new LinkedHashMap<String, String>();
        params.put("origin", shopLocation);
        params.put("destination", userLocation);
        params.put("riding_type", "1");
        params.put("ak", AK);
        //发送请求 获得JSON
        String getDistance = HttpClientUtil.doGet(RIDE_URL, params);
        //解析JSON
        JSONObject jsonObject = JSONObject.parseObject(getDistance);
        //status!=0 抛异常
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }
        //result distance 方案距离 单位：米
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray routes = result.getJSONArray("routes");
        Integer distance = ((JSONObject) routes.get(0)).getInteger("distance");

        if (distance < range) {
            return true;
        }
        return false;

    }
}
